<template>
    <div class="supping-car">
      <Header :getGoods="getGoods"  />
      <div class="supping-main">
        <div class="supping-main-left">
          <div class="car-summary">
            <div class="summary-header">
              <span>全部商品({{ carGoods.length }})</span>
            </div>
            <div class="select-all-container">
              <label class="select-all">
                <input class="checkALL" type="checkbox" v-model="selectAll" @change="toggleSelectAll" />
              </label>
              <p>全选</p>
              <button class="delete-btn" @click="confirmAndDeleteSelectedItems">删除</button>
            </div>
          </div>
          <div v-if="carGoods.length === 0">购物车为空</div>
          <div v-else>
            <div v-for="(item, index) in carGoods" :key="index" class="car-item" @click="toggleItemSelection(item)">
              <input type="checkbox" v-model="selectedItems" :value="item" class="item-checkbox" />
              <img :src="item.imgPath" alt="goodsImg" class="item-img"/>
              <div class="item-info">
                <h3 class="item-name">{{ item.goodsName }}</h3>
                <p class="item-price">价格: ¥{{ item.price.toFixed(2) }}</p>
              </div>
            </div>
          </div>
        </div>
        <div class="supping-main-right">
          <h3>已选商品: {{ selectedItems.length }} 件</h3>
          <div class="selected-items-preview">
            <div v-for="item in selectedItems" :key="item.goodsId" class="preview-item">
              <img :src="item.imgPath" alt="SelectGoods" class="preview-img"/>
            </div>
          </div>
          <div class="summary">
            <h3>总价格: ¥{{ totalPrice.toFixed(2) }}</h3>
            <button class="purchase-btn" @click="purchaseItems">购买</button>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import Header from './Header.vue';
  import { ref, onMounted, watch, computed } from 'vue';
  import axios from 'axios';
  import { useRouter } from 'vue-router';
  import '../css/car.css'
  
  interface CarGoods {
    goodsId: number;  
    userName: string;
    price: number;
    imgPath: string;
    goodsName: string;
    categories: string;
  }
  
  const confirmDelete = ref(false);
  const carGoods = ref<CarGoods[]>([]);
  const selectedItems = ref<CarGoods[]>([]);
  const selectAll = ref(false);
  const userId = localStorage.getItem('userId');
  const router = useRouter();
  const getCarGoodsLink = "http://localhost:8080/goods/getCarGoods";
  const deleteCarGoodsLink = "http://localhost:8080/goods/deleteCarGoods";
  const token = localStorage.getItem('token');
  
  // 计算总价格
  const totalPrice = computed(() => {
    return selectedItems.value.reduce((sum, item) => sum + item.price, 0);
  });
  
  const getCarGoods = async () => {
    if (!token) {
      router.push({ name: 'Login' });
    } else {
      try {
        const response = await axios.post(getCarGoodsLink, userId, {
          headers: { 
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
        });
        
        carGoods.value = response.data.data; 
        selectAll.value = carGoods.value.length > 0 && selectedItems.value.length === carGoods.value.length;
      } catch (error) {
        console.error('获取购物车商品失败:', error);
        alert('获取购物车商品失败，请稍后再试。');
      }
    }
  }
  
  const toggleSelectAll = () => {
    if (selectAll.value) {
      selectedItems.value = [...carGoods.value];
    } else {
      selectedItems.value = [];
    }
  };
  
  watch(selectedItems, (newSelectedItems) => {
    selectAll.value = newSelectedItems.length === carGoods.value.length;
  }, { immediate: true });
  
  const toggleItemSelection = (item: CarGoods) => {
    const index = selectedItems.value.findIndex(selectedItem => selectedItem.goodsId === item.goodsId);
    if (index > -1) {
      selectedItems.value.splice(index, 1);
    } else {
      selectedItems.value.push(item);
    }
    selectAll.value = selectedItems.value.length === carGoods.value.length;
  };
  
  const confirmAndDeleteSelectedItems = () => {
    if (confirm('确定要删除选中的商品吗？')) {
      confirmDelete.value = true;
      deleteSelectedItems();
    } else {
      confirmDelete.value = false;
    }
  };
  
  const deleteSelectedItems = async () => {
    if (!confirmDelete.value) return;
  
    if (!userId) {
      alert('用户未登录');
      return;
    }
    
    const selectedGoodsIds = selectedItems.value.map(item => item.goodsId);
    if (selectedGoodsIds.length === 0) {
      alert('没有选中任何商品');
      return;
    }
    
    try {
      const deleteCarGoodsDao = {
        userId,
        goodsId: selectedGoodsIds 
      }
      const response = await axios.post(deleteCarGoodsLink, deleteCarGoodsDao, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
      });
      const result = response.data;
      const state = result.state;
      const errMessage = result.errMessage;
      if (state) {
        selectedItems.value = [];
        getCarGoods();
      } else {
        alert(errMessage);
      }
    } catch (error) {
      console.error('删除商品失败:', error);
      alert('删除商品失败，请稍后再试。');
    } finally {
      confirmDelete.value = false; 
    }
  };
  
  // 购买商品的方法
const purchaseItems = async () => {
  if (selectedItems.value.length === 0) {
    alert('没有选中任何商品');
    return;
  }
  
  // 收集选中的商品ID
  const selectedGoodsIds = selectedItems.value.map(item => item.goodsId);
      confirmDelete.value = true;
      deleteSelectedItems();
  try {
    // 如果删除成功，跳转到购买页面
    router.push({ name: 'Buy', query: { ids: selectedGoodsIds.join(',') } });
  } catch (error) {
    console.error('购买商品失败:', error);
    alert('购买商品失败，请稍后再试。');
  }
};

defineProps<{
  getGoods: (filterObject: { name: string; platform: string; sortType: string; categoriesId: number }) => void;
}>();

onMounted(() => {
    getCarGoods();
  });
  </script>
  
  
  